#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
    发送邮件（应用场景为程序除错或者发生特定事件时的通知邮件，不适用于大量发送）
"""

from email.mime.text import MIMEText
import sys
import smtplib

from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart


reload(sys)
sys.setdefaultencoding("utf-8")


_DEFAULT_SENDER_HOST = 'smtp.sina.com'          # 默认服务器
_DEFAULT_SENDER_MAIL = 'yucuntest123@sina.com'  # 默认用户
_DEFAULT_SENDER_PASS = 'yucuntest'              # 默认密码
_DEFAULT_SENDER_NICK = 'xawesome_mail'          # 默认发件人名称


def _trans_2_unicode(string):
    """
    将一个string转化为unicode字符串
    :param string:
    :return:
    """
    if isinstance(string, unicode):
        return string
    return unicode(string)


def _deal_mail_list(mail_list):
    return [mail if '@' in mail else mail + '@socialcredits.cn' for mail in mail_list]


def send_mail(subject, content, mailto_list, **kwargs):
    """
    发送邮件（所有参数皆可使用unicode或者str格式）
    :param subject    : 邮件主题
    :param content    : 邮件正文
    :param mailto_list: 邮件接收者列表
    :param kwargs: 关键字参数（ATT: 后面三个参数必须同时指定或者同时不指定）：
                sender_nickname ： 发件人昵称
                sender_mail_addr： 定制发件人邮件地址
                sender_mail_pass： 定制发件人邮箱密码
                sender_mail_host： 定制发件人邮箱服务器
    :return: True：发送成功； False：发送失败
    """
    mailto_list = _deal_mail_list(mailto_list)
    # 处理编码
    subject = _trans_2_unicode(subject)
    content = _trans_2_unicode(content)
    for key in kwargs:
        kwargs[key] = _trans_2_unicode(kwargs[key])

    # 获取 kwargs 参数
    sender_nickname = _DEFAULT_SENDER_NICK if 'sender_nickname' not in kwargs else kwargs['sender_nickname']
    sender_mailaddr = _DEFAULT_SENDER_MAIL if 'sender_mail_addr' not in kwargs else kwargs['sender_mail_addr']
    sender_mailpass = _DEFAULT_SENDER_PASS if 'sender_mail_pass' not in kwargs else kwargs['sender_mail_pass']
    sender_mailhost = _DEFAULT_SENDER_HOST if 'sender_mail_host' not in kwargs else kwargs['sender_mail_host']

    from_user = '{nick}<{mail}>'.format(nick=sender_nickname, mail=sender_mailaddr)

    # 构建邮件
    message = MIMEText(content, _subtype='plain', _charset='utf-8')
    message['Subject'] = subject
    message['From'] = from_user
    message['To'] = ';'.join(mailto_list)
    try:
        # 发送邮件
        server = smtplib.SMTP()
        server.connect(sender_mailhost)
        server.login(sender_mailaddr.split('@')[0], sender_mailpass)
        server.sendmail(from_user, mailto_list, message.as_string())
        server.quit()
        return True
    except Exception, e:
        print e
        return False


if __name__ == '__main__':
    print _deal_mail_list(['xu.du', 'wu.zheng@socialcredits.cn'])
    # print send_mail('中文主题', u'中文正文', ['xu.du'], sender_nickname='test')